﻿using NHibernate;
using NHibernate.Cfg;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Model.NHExtras
{
    public sealed class NHibernateHelper
    {
        private static ISession CurrentSession;
        private static IStatelessSession CurrentStatelessSession;
        private static ISessionFactory _SessionFactory { get; set; }
        private static ISessionFactory SessionFactory
        {
            get
            {
                if (NHibernateHelper._SessionFactory == null)
                {
                    string connstr = Utils.Conexao.BuildConnectionString();
                    NHibernateHelper._SessionFactory = new Configuration()
                                                        .SetProperty("connection.connection_string", connstr)
                                                            .Configure()
                                                                .BuildSessionFactory();
                }

                return NHibernateHelper._SessionFactory;
            }
        }

        public static ISession GetCurrentSession()
        {
            if (NHibernateHelper.CurrentSession == null)
            {
                NHibernateHelper.CurrentSession = NHibernateHelper.SessionFactory.OpenSession();
            }
                //Não sei se posso fazer isso... mas
            else if (NHibernateHelper.CurrentSession.IsOpen != true)
            {
                NHibernateHelper.CurrentSession.Dispose();
                NHibernateHelper.CurrentSession = NHibernateHelper.SessionFactory.OpenSession();
            }

            return NHibernateHelper.CurrentSession;
        }

        public static IStatelessSession GetCurrentStatelessSession()
        {
            if (NHibernateHelper.CurrentStatelessSession == null)
            {
                NHibernateHelper.CurrentStatelessSession = NHibernateHelper.SessionFactory.OpenStatelessSession();
            }
            //Não sei se posso fazer isso... mas
            else if (NHibernateHelper.CurrentStatelessSession.IsOpen != true)
            {
                NHibernateHelper.CurrentStatelessSession.Dispose();
                NHibernateHelper.CurrentStatelessSession = NHibernateHelper.SessionFactory.OpenStatelessSession();
            }

            return NHibernateHelper.CurrentStatelessSession;
        }

        public static void CloseSession()
        {
            if (NHibernateHelper.CurrentSession == null)
            {
                return;
            }

            NHibernateHelper.CurrentSession.Close();
        }

        public static void CloseSessionFactory()
        {
            if (NHibernateHelper.SessionFactory != null)
            {
                NHibernateHelper.SessionFactory.Close();
            }
        }
    }
}